import axios from 'axios'
import router from '../router'
import { Message, MessageBox, Loading } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import qs from 'qs';

// 创建axios实例
const service = axios.create({
  // api的base_url 或 proxyTable代理模式 /testapi/
  baseURL: process.env.NODE_ENV === 'development' ? process.env.BASE_API : process.env.BASE_API, // api的base_url 或 proxyTable代理模式
  timeout: 10 * 1000, // 请求超时时间
  transformRequest: [
    function(data) {
      data = qs.stringify(data);
      return data;
    }
  ],
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})

let loadingInstance = null;
const requestUrlArr = ["/login", "/user/list", "/role/list", "/systemconfig/list", "/device/list", "/product/list/", "/device/count", "/review/devicelist"]; //不需要显示全屏loading的接口

// request拦截器
service.interceptors.request.use(config => {
  if (!requestUrlArr.includes(config.url)) {
    loadingInstance = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  }
  if (store.getters.token) {
    config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    if (loadingInstance) {
      loadingInstance.close();
    }
    const res = response
    if (res.status !== 200) {
      if (res.status === 401) {
        MessageBox.confirm('登录已失效或过期，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else {
        Message({
          message: res.data.message || '未知错误，请联系管理员',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject('error')
    } else {
      return res
    }
  },
  error => {
    if (loadingInstance) {
      loadingInstance.close();
    }
    console.log('err' + error) // for debug
    if (error.response.status === 401) {
      showErrorMessage(error);
      var routerName = location.pathname;
      if(routerName !== "/login") {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
          return;
        })
      }
    } else {
      showErrorMessage(error);
    }
    return Promise.reject(error)
  }
)

function showErrorMessage(error){
  Message({
    message: !error.response ? error.message : (Object.prototype.toString.call(error.response.data) == "[object Object]" ? error.response.data.message : "参数有误，服务器无法识别当前请求"),
    type: 'error',
    duration: 3 * 1000
  })
}

export default service
